<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>基于以太坊的大海筹-众筹项目</title>
    <script src="../js/jquery.min.js"></script>
    <script src="../js/web3.min.js"></script>
    <script src="../js/bootstrap4.0.0.min.js"></script>
    <script src="../js/bootstrap.bundle.min.js"></script>
    <link href="../css/bootstrap@5.0.0-beta1.min.css" rel="stylesheet" crossorigin="anonymous">
    <!--    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>-->
    <!--    <script src="https://cdn.jsdelivr.net/npm/jquery@3.3.1/dist/jquery.min.js"></script>-->
    <!--    <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.3.5/dist/web3.min.js"></script>-->
    <!--    <script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>-->
    <!--    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet"-->
    <!--          integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">-->
    <style>
        .t1 {
            text-align: center;
            margin-top: 30px;
        }

        .t2 {
            text-align: center;
        }

        .body-margin {
            margin-left: 5%;
            margin-right: 5%;
            margin-bottom: 100px
        }

        .t2-margin {
            margin-top: 50px
        }

        .modal-content {
            color: #5e5e5e;
            width: fit-content;
            min-width: 300px;
            background-color: white;
            padding: 0.4rem 0.4rem;
        }

        .button-width {
            width: 100px;
        }

        .link {
            color: #0a53be;
            font-weight: bold;
            text-decoration: none;
        }
    </style>
</head>

<body class="body-margin">

<div class="modal fade bd-example-modal-sm" id="msg" role="dialog" data-backdrop="false" aria-hidden="false">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <p class="text-center mb-0">
                <i class="fa fa-check-circle text-success mr-1" aria-hidden="true"></i>
                <span id="msgContent"></span>
            </p>
        </div>
    </div>
</div>

<div class="t1">
    <h1>基于以太坊的大海筹-众筹项目</h1>
</div>

<h5 class="page-header t2-margin"></h5>
<h2 class="t2">申请人</h2>
<table class="table">
    <thead>
    <tr>
        <th scope="col">ID</th>
        <th scope="col">账户</th>
        <th scope="col">姓名</th>
        <th scope="col">众筹原因</th>
        <th scope="col">目标金额(wei)</th>
        <th scope="col">当前总额(wei)</th>
        <th scope="col">捐赠人次</th>
    </tr>
    </thead>
    <tbody id="dataTable"></tbody>
</table>


<h5 class="page-header t2-margin"></h5>
<h2 class="t2"> 申请众筹 </h2>
<div>
    <div class="mb-3">
        <label for="applyName" class="form-label">您的名字</label>
        <input type="text" class="form-control" id="applyName" placeholder="您的名字">
    </div>
    <div class="mb-3">
        <label for="applyReason" class="form-label">您的情况</label>
        <input type="text" class="form-control" id="applyReason" placeholder="描述您的情况和众筹资金用途">
    </div>
    <div class="mb-3">
        <label for="applyMoney" class="form-label">申请金额(wei)</label>
        <input type="number" class="form-control" id="applyMoney" placeholder="您需要的额度">
    </div>
    <div class="text-center">
        <button id="newNeeder" class="btn btn-primary btn-user btn-block button-width">申请</button>
    </div>
</div>


<h5 class="page-header t2-margin"></h5>
<h2 class="t2"> 我要捐赠 </h2>
<div>
    <div class="mb-3">
        <label for="targetAddressId" class="form-label">众筹人ID</label>
        <input type="text" class="form-control" id="targetAddressId" placeholder="请填写第一列ID，不要填写账户地址">
    </div>
    <div class="mb-3">
        <label for="money" class="form-label">捐赠金额(wei)</label>
        <input type="number" class="form-control" id="money" placeholder="0">
    </div>
    <div class="text-center">
        <button id="contribute" class="btn btn-primary btn-user btn-block button-width">捐赠</button>
    </div>
</div>


<h5 class="page-header t2-margin"></h5>
<h2 class="t2"> 账号相关 </h2>
<div>
    <div>
        登陆账号地址: <span id="currentAccount"></span>
    </div>
    <div>
        合约地址：0xcafD5ee09172307E191EF4a1646a0d34Bc942d5e
    </div>
    <div>
        Rinkeby领币网站：https://faucets.chain.link/rinkeby, https://faucet.rinkeby.io
    </div>
    <div>
        源码链接：https://gitee.com/hbuzzs/crowd-funding-fe
    </div>
    <div>
        Web3客户端版本: <span id="web3ClientVersion"></span>
    </div>
    <div>
        测试网络: Ethereum Rinkeby
    </div>
    <div>
        <a id="authorization" class="link">> 点击重新授权钱包</a>
    </div>
</div>

<!-- Button trigger modal -->
<button id="launchModal" type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModal" hidden="hidden">
</button>
<!-- Scrollable modal -->
<!-- Modal -->
<div class="modal fade" id="myModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1"
     aria-labelledby="staticBackdropLabel" aria-hidden="false">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="staticBackdropLabel">DApp提示</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                此DApp依赖测试网络Ethereum Rinkeby和MetaMask钱包，请检查是否满足条件
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<script src="../conf/base_conf.js"></script>

<script>

    // 弹出消息
    function msg(msg) {
        $("#msgContent").text(msg);
        $('#msg').modal("show");
        console.log(msg);
        setTimeout(function () {
            $("#msg").modal("hide");
        }, 2500);
    }

    // 读取abi.json
    function makeRequest(method, url) {
        return new Promise(function (resolve, reject) {
            let xhr = new XMLHttpRequest();
            xhr.open(method, url);
            xhr.onload = function () {
                if (this.status >= 200 && this.status < 300) {
                    resolve(xhr.response);
                } else {
                    reject({
                        status: this.status,
                        statusText: xhr.statusText
                    });
                }
            };
            xhr.onerror = function () {
                reject({
                    status: this.status,
                    statusText: xhr.statusText
                });
            };
            xhr.send();
        });
    }

    // 授权钱包
    function authorization() {
        let web3Provider;
        // 检查是否是新的 MetaMask 或 DApp 浏览器
        if (window.ethereum) {
            web3Provider = window.ethereum;
            try {
                // 请求用户授权
                window.ethereum.enable();
                web3 = new Web3(web3Provider);
                msg("钱包授权成功");
                return true;
            } catch (error) {
                // 用户不授权时
                console.error("User denied account access");
                alert("您未授权钱包，请检查是否切换到Ethereum Rinkeby网络并点击页面最下方重新授权");
                return false;
            }
        } else {
            alert("授权失败，请安装最新版MetaMask钱包或DApp浏览器");
            return false
        }

    }

    // 获取所有数据
    async function getAllInfo() {
        //此处需要让其动态的生成一个table并填充数据
        let tableStr = "";
        contract = new web3.eth.Contract(abi, STORAGE_CONTRACT_ID);
        // TODO 这里暂时这样，以后可以分页
        for (let i = 1; i < 100; i++) {
            retrieve = await contract.methods.showNeeder(i).call();
            if (retrieve[0] !== ADDRESS_0) {
                console.log(retrieve);
                tableStr = tableStr + "<tr><th scope='row'>" + i + "</th>"
                    + "<td align='left'>" + retrieve[0] + "</td>"
                    + "<td align='left'>" + retrieve[1] + "</td>"
                    + "<td align='left'>" + retrieve[2] + "</td>"
                    + "<td align='left'>" + retrieve[3] + "</td>"
                    + "<td align='left'>" + retrieve[4] + "</td>"
                    + "<td align='left'>" + retrieve[5] + "</td></tr>";
            } else {
                break;
            }
        }
        //将动态生成的table添加的事先隐藏的div中.
        $("#dataTable").html(tableStr);
    }

    // 设置其他信息
    async function setOtherInfo() {
        version = await ethereum.request({method: "web3_clientVersion"});
        console.log("setOtherInfo");
        requestAccounts = await ethereum.request({method: 'eth_requestAccounts'});
        console.log(version);
        console.log(requestAccounts);
        $("#web3ClientVersion").text(version);
        $("#currentAccount").text(requestAccounts);
    }

    // 初始化页面
    async function initPage(){
        jsonStr = await makeRequest("GET", STORAGE_ABI_PATH);
        abi = JSON.parse(jsonStr);
        await setOtherInfo();
        await getAllInfo();
    }

    // 初始化数据
    $(async function () {
        const launchModal = document.getElementById('launchModal');
        launchModal.click();
        const myModalEl = document.getElementById('myModal');
        myModalEl.addEventListener('hidden.bs.modal', async function (event) {
            console.log("event:" + event);
            if (authorization()) {
                try {
                    await initPage()
                } catch (error) {
                    alert("初始化页面数据失败\n可能由于钱包连接失败或未切换到Rinkeby网络");
                }
            }
        })
    });

    // 申请
    $("#newNeeder").click(async function () {
        jsonStr = await makeRequest("GET", STORAGE_ABI_PATH);
        abi = JSON.parse(jsonStr);
        contract = new web3.eth.Contract(abi, STORAGE_CONTRACT_ID);
        requestAccounts = await ethereum.request({method: 'eth_requestAccounts'});
        console.log(requestAccounts);
        applyName = $('#applyName')[0].value;
        applyReason = $('#applyReason')[0].value;
        applyMoney = $('#applyMoney')[0].value;
        console.log(applyName + ", " + applyReason + ". 申请金额: " + applyMoney);
        contract.methods.newNeeder(applyName,applyReason,applyMoney).send({from: requestAccounts[0]})
            .on('transactionHash', function (hash) {
                console.log("transactionHash");
                console.log(hash);
                alert("提交成功！交易Hash:" + hash);
                location.reload();
            })
            .on('confirmation', function (confirmationNumber, receipt) {
                console.log("confirmation");
                console.log(confirmationNumber);
                console.log(receipt);
            })
            .on('receipt', function (receipt) {
                // receipt example
                console.log("receipt");
                console.log(receipt);
            })
            .on('error', function (error, receipt) {
                // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
                console.log("error");
                console.log(error);
                console.log(receipt);
                alert("错误：" + error);
            });
    });

    // 捐赠
    $("#contribute").click(async function () {
        jsonStr = await makeRequest("GET", STORAGE_ABI_PATH);
        abi = JSON.parse(jsonStr);
        contract = new web3.eth.Contract(abi, STORAGE_CONTRACT_ID);
        requestAccounts = await ethereum.request({method: 'eth_requestAccounts'});
        console.log(requestAccounts);
        targetAddressId = $('#targetAddressId')[0].value;
        money = $('#money')[0].value;
        console.log(requestAccounts + " -> " + targetAddressId + " : " + money);
        contract.methods.contribute(targetAddressId).send({from: requestAccounts[0], value: money})
            .on('transactionHash', function (hash) {
                console.log("transactionHash");
                console.log(hash);
                alert("提交成功！交易Hash:" + hash);
                location.reload();
            })
            .on('confirmation', function (confirmationNumber, receipt) {
                console.log("confirmation");
                console.log(confirmationNumber);
                console.log(receipt);
            })
            .on('receipt', function (receipt) {
                // receipt example
                console.log("receipt");
                console.log(receipt);
            })
            .on('error', function (error, receipt) {
                // If the transaction was rejected by the network with a receipt, the second parameter will be the receipt.
                console.log("error");
                console.log(error);
                console.log(receipt);
                alert("错误：" + error);
            });
    });

    // 重新授权钱包
    $("#authorization").click(async function () {
        authorization();
        await initPage()
    })

</script>

</body>
